﻿
var crypto = require('crypto');
var fs = require('fs');
var privatePem = fs.readFileSync('server.pem');
var publicPem = fs.readFileSync('cert.pem');

function content(c) {
    var key;
    if (c == "public")
        key = publicPem.toString();
    else if (c == "private")
        key = privatePem.toString();
    return key;
}
function encode(text) {
    var cipher = crypto.createCipher('aes192', content("public"));
    var crypted = cipher.update(text, 'utf8', 'hex')
    crypted += cipher.final('hex')
    return crypted;
}
function decode(crypted) {
    var decipher = crypto.createDecipher('aes192', content("public"));
    var dec = decipher.update(crypted, 'hex', 'utf8')
    dec += decipher.final('utf8')
    return dec;
}
//认证
function encode_rsa_sign(data) {
    var sign = crypto.createSign('RSA-SHA256');
    sign.update(data);
    var sig = sign.sign(content("private"), 'hex');
    return sig;
}

function decode_rsa_verify(data, sig) {
    var verify = crypto.createVerify('RSA-SHA256');
    verify.update(data);
    return verify.verify(content("public"), sig, 'hex');
}
function encode_1(text) {
    var cipher = crypto.createCipher('aes192', '123');
    var crypted = cipher.update(text, 'utf8', 'hex')
    crypted += cipher.final('hex')
    return crypted;
}
function decode_1(crypted) {
    var decipher = crypto.createDecipher('aes192', '123');
    var dec = decipher.update(crypted, 'hex', 'utf8')
    dec += decipher.final('utf8')
    return dec;
}


//var test = crypto.privateEncrypt(privatePem.toString(), buffer.from("qianbo"));
//console.log(test);
//crypto.privateEncrypt
var text_connect = {
    host: '118.190.203.202',
    user: 'root',
    password: 'root',
    database: 'construction',
    port: '3306',
    timezone: '+08:00'
}
var local_connect ={
    host:'localhost',
    user:'root',
    password:'root',
    database:'construction',
    port:'3306',
    timezone: '+08:00'
};


function encode_Connect(text) {
    var encrypt = encode(text);
    var sig = encode_rsa_sign(encrypt);
    return {encrypt:encrypt,sig:sig};
}
//sig 签名

function decode_Connect(encrypt,sig) {
    var c = null;
    var ret = decode_rsa_verify(encrypt, sig);
    if (ret) {
        c = decode(encrypt);
    }
    return c;
}


var text = JSON.stringify(text_connect);
console.log(text);
var obj = encode_Connect(text);
console.log(obj);
var ret = decode_Connect(obj.encrypt, obj.sig);
console.log(ret);
var dd = JSON.parse(ret);
console.log(dd);
